package com.softwin.cryptocurrency.demo.ma;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Xiao Yang on 2018/07/03.
 */
public class MaCalculator {
    private final Queue<BigDecimal> window = new LinkedList<>(); // First in First Out
    private final int period;
    private BigDecimal sum = BigDecimal.ZERO;

    public MaCalculator(int period){
        assert period > 0 : "Period must be a positive integer";
        this.period = period;
    }
    public void newNum(BigDecimal num) {
        sum = sum.add(num);
        window.add(num);
        if (window.size() > period) {
            sum = sum.subtract(window.remove());
        }
    }

    public BigDecimal getAvg() {
        if (window.size() != period)
            return BigDecimal.ZERO; // technically the average is undefined
        return sum.divide(new BigDecimal(window.size()), 8, RoundingMode.HALF_UP);
    }
}
